package show.me.the.money.config.reportSchema;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;

import show.me.the.money.config.ConfigController;
import show.me.the.money.config.MultiConfigController;
import show.me.the.money.config.reportSchema.define.ReportSchema;
import show.me.the.money.config.reportSchema.define.ReportTypeUtil;
import show.me.the.money.util.context.Context;



public class ReportSchemaController extends MultiConfigController{
	private static Log logger = LogFactory.getLog(ReportSchemaController.class);
	private static ReportSchemaController rsc;
	
	private ReportSchemaController(){
		CATALOG = ConfigController.CATA_RTSCHEMA;
	} 
	
	public static ReportSchemaController instance(){
		if(rsc == null){
			rsc = new ReportSchemaController();
		}
		return rsc;
	}
	
	public  ReportSchema getSchema(String id){
		if(defineDoc == null){
			return null;
		}
		ReportSchema schema = (ReportSchema)cache.get(id);
		if(schema == null){
			Document doc = getConfigDoc(id);
			if(doc != null){
				try {
					schema = new ReportSchema();
					schema.setDefineDoc(doc);
				}
				catch (Exception e) {
					e.printStackTrace();
					logger.fatal("can't init reportSchema for[" + id + "]:", e);
				}
			}
			else{
				logger.error("reportSchema [" + id + "] load failed.");
			}
		}
		return schema;
	}
	
	public ReportSchema getSchemaDynamic(String id, Context ctx) {
		if (defineDoc == null) {
			return null;
		}
		ReportSchema schema = (ReportSchema) cache.get(id);
		if (schema == null) {
			Document doc = getConfigDoc(id);
			if (doc != null) {
				Element el = doc.getRootElement();
				// String cls = el.attributeValue("class");
				try {
					if (el.attributeValue("type") == null) {
						schema = new ReportSchema();
					} else {
						String clsName = el.attributeValue("type");
						if (ReportTypeUtil.hasType(clsName)) {
							clsName = "ctd.config.reportSchema.define."+ReportTypeUtil.getReportClass(clsName);
						}

						if (!StringUtils.isEmpty(clsName)) {
							try {
								schema = (ReportSchema) Class.forName(clsName)
										.newInstance();
							} catch (Exception e) {
								e.printStackTrace();
								logger.error("ReportDefine for [" + clsName
										+ "] create instance failed:", e);
							}

						}
					}
					schema.setDefineDoc(doc, ctx);
				} catch (Exception e) {
					e.printStackTrace();
					logger.fatal("can't init reportSchema for[" + id + "]:", e);
				}
			} else {
				logger.error("reportSchema [" + id + "] load failed.");
			}
		}
		return schema;
	}

}
